<template>
  <div class="container">
    <el-form
      label-width="80px"
      :model="addTagForm"
      :rules="addTagFormRules"
      ref="addTagForm"
    >
      <el-form-item label="所属学科" v-if="!$route.query.id">
        <el-select v-model="addTagForm.subjectId" placeholder="请选择">
          <el-option
            v-for="(subject,subjectIndex) in subjectsList"
            :key="subjectIndex"
            :label="subject.subjectName"
            :value="subject.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签名称" prop="tagName" class="tagName">
        <el-input v-model="addTagForm.tagName" placeholder="请输入内容" class="tagInput"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$emit('close')">取 消</el-button>
      <el-button type="primary" @click="submitForm('addTagForm')">确 定</el-button>
    </span>
  </div>
</template>

<script>
// 学科列表
import { list } from '@/api/hmmm/subjects.js'
// 标签添加
import { add } from '@/api/hmmm/tags.js'

export default {
  name: 'tagsAdd',
  data () {
    return {
      // 添加目录表单数据
      addTagForm: {
        subjectId: '',
        tagName: ''
      },
      addTagFormRules: {
        tagName: [
          { required: true, message: '请输入标签名称', trigger: 'blur' }
        ]
      },
      // 学科列表数据
      subjectsList: []
    }
  },
  methods: {
    // 获取学科列表
    async getSubjectList () {
      const { data: res } = await list({
        pagesize: 20
      })
      this.subjectsList = res.items
    },
    // 添加标签
    submitForm (addTagForm) {
      this.$refs.addTagForm.validate(async (valid) => {
        if (valid) {
          if (this.$route.query.id) {
            await add({
              subjectID: this.$route.query.id,
              tagName: this.addTagForm.tagName
            })
          } else {
            await add({
              subjectID: this.addTagForm.subjectId,
              tagName: this.addTagForm.tagName
            })
          }
          this.$emit('close')
          this.$message.success('操作成功')
        } else {
          return false
        }
      })
    }
  },
  created () {
    // 获取学科列表
    this.getSubjectList()
  }
}
</script>

<style scoped lang='scss'>
.tagInput{
max-width: 70%;
min-width: 30%;
}
.tagName {
  width: 75%;
}
</style>
